package com.edeweiss.community.dao.daoImp;

import com.edeweiss.community.dao.ReportDao;
import com.edeweiss.community.domain.Message;
import com.edeweiss.community.domain.Report;
import com.edeweiss.community.web.utils.JDBCUtils;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanListHandler;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.Date;
import java.util.List;

public class ReportDaoImpl implements ReportDao {
    QueryRunner qr = new QueryRunner(JDBCUtils.getDataSource());

    @Override
    public int report(Report report) {
        int i = 0;
        String sql = "insert into report (sid,content,time) values (?,?,?)";
        Object[] params = {report.getSid(),report.getContent(),report.getTime()};
        try {
           i = qr.update(sql,params);
        } catch (SQLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return i;
    }

    @Override
    public List<Report> findAll() {
        String sql = "select * from report where status = 0";
        List<Report> reports = null;
        try {
            reports = qr.query(sql, new BeanListHandler<Report>(Report.class));
        } catch (SQLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return reports;
    }

    @Override
    public int answer(Message m, int rid) {
        int flag = 0;
        String sql1 = "update report set status = ? where rid = ?";
        String sql2 = "insert into message (sid,message,status,time) values (?,?,?,?)";
        Connection conn = JDBCUtils.getConnection();
        try {
            //开启事务
            JDBCUtils.startTransaction(conn);
            PreparedStatement st = conn.prepareStatement(sql1);
            st.setInt(1,1);
            st.setInt(2,rid);
            st.executeUpdate();

            st = conn.prepareStatement(sql2);
            st.setString(1,m.getSid());
            st.setString(2,m.getMessage());
            st.setInt(3,0);
            java.sql.Date date = new java.sql.Date(new Date().getTime());
            st.setDate(4,date);
            st.executeUpdate();
            //提交事务
            JDBCUtils.commitTransaction(conn);
            flag=1;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return flag;
    }
}
